package com.emep.emeptime.controller;

import com.emep.emeptime.model.ApiData;
import com.emep.emeptime.model.ChinaRankings;
import com.emep.emeptime.service.AQIIactorInfoService;
import com.emep.emeptime.service.AreaAqiMoniterService;
import com.emep.emeptime.service.WeatherService;
import com.emep.emeptime.service.aqi.AqiNumberOfDaysService;
import com.emep.emeptime.utils.DateUtils;
import com.emep.emeptime.utils.GsonUtils;
import com.emep.emeptime.utils.HttpUtil;
import com.emep.emeptime.utils.Quantity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jayway.jsonpath.JsonPath;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author xieyang
 * @Description: 排名定时器
 * @date 2018/3/23 17:15
 * @version V1.0
 */
@Slf4j
@Component
public class ScheduledController {

    @Autowired
    private AQIIactorInfoService aqiIactorInfoService;

    //@Scheduled(cron="0 0 1 * * ?")
   //@Scheduled(cron="0/2 * * * * *") //每两秒运行
    @Scheduled(cron="0 55 0/1 * * ?")  //每小时的55分运行
    public void getDatasync(){
         try {
             OkHttpClient client = new OkHttpClient.Builder()
                     .connectTimeout(5, TimeUnit.SECONDS)
                     .writeTimeout(10, TimeUnit.SECONDS)//写入超时
                     .readTimeout(5, TimeUnit.SECONDS)
                     .build();
             Request request = new Request.Builder()
                     .url(Quantity.CHINA)
                     .build();
             Response response = null;
             response = client.newCall(request).execute();
             if (response.isSuccessful()) {
                     log.info("***************** 【排名HTTP 请求成功】请求返回状态:=={},时间:=={}", response.code(), DateUtils.getNowTime());
//                     HashMap<String,String> idMap1 = new HashMap<String,String>(Quantity.DEFAULT_INITIAL_CAPACITY);
//                     idMap1.put("cid","140400");
//                     idMap1.put("dt", DateUtils.DateToString());
//                     idMap1.put("?_st", String.valueOf(System.currentTimeMillis()));
                     //String  chinaRankings = HttpUtil.sendGet(Quantity.CHINA_SHENG,idMap1);
                 List<ChinaRankings> apiData =new Gson().fromJson(response.body().string(), new TypeToken<List<ChinaRankings>>(){}.getType());
                 aqiIactorInfoService.saveChina(apiData);
             }else {
                 log.error("***************** 【监控数据HTTP 请求失败！！！】 请求状态:=={},时间:=={}", response.code(),DateUtils.getNowTime());
             }
         } catch (Exception e) {
             e.printStackTrace();
         }
    }
}